// intercodegenerate.c
#define _CRT_SECURE_NO_WARNINGS 1 

#include "intercodegenerate.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// 全局中间代码列表
InterCode ir_codes[MAX_LINE];
int ir_count = 0;

/*---------- 全局计数器 ----------*/
static int temp_counter = 1;  // 临时变量计数器
static int label_counter = 1; // 标签计数器

// 安全字符串复制
#ifdef _MSC_VER
#define safe_strdup _strdup
#else
#define safe_strdup strdup
#endif

// 操作数创建函数及释放函数
Operand create_var_operand(const char* name) {
    printf("[DEBUG] Creating variable operand: %s\n", name); // 添加调试输出

	Operand op = (Operand)malloc(sizeof(struct Operand_));

    printf("[OPERAND] Creating operand for '%s' at %p\n", name, (void*)op);

	op->kind = VARIABLE;
	op->u.name = safe_strdup(name);
	return op;
}

Operand create_const_operand(int value) {
	Operand op = (Operand)malloc(sizeof(struct Operand_));
	op->kind = CONSTANT;
	op->u.value = value;
	return op;
}

Operand create_label_operand(int no) {
	Operand op = (Operand)malloc(sizeof(struct Operand_));
	op->kind = LABEL;
	char buffer[20];
	sprintf(buffer, "label%d", no);
	op->u.name = safe_strdup(buffer);
	return op;
}

Operand create_relop_operand(const char* op) {
	Operand o = (Operand)malloc(sizeof(struct Operand_));
	o->kind = RELOP;
	o->u.name = safe_strdup(op);
	return o;
}

void free_operand(Operand op) {
	if (!op) return;
	if (op->kind == VARIABLE || op->kind == LABEL || op->kind == RELOP) {
		free(op->u.name);
	}
	free(op);
}


// ====================== 核心生成函数 ======================
void gen_assign(Operand left, Operand right) {

    char* left_str = operand_to_str(left);
    char* right_str = operand_to_str(right);

    printf("[DEBUG] Generating ASSIGN: %s := %s\n", left_str, right_str); // 添加调试输

    free(left_str);
    free(right_str);

	InterCode code;
	code.kind = ASSIGN;
	code.u.assign.left = left;
	code.u.assign.right = right;
	ir_codes[ir_count++] = code;
}

void gen_binop(int kind, Operand res, Operand op1, Operand op2) {
	InterCode code;
	switch (kind) {
	case ADD: code.kind = ADD; break;
	case SUB: code.kind = SUB; break;
	case MUL: code.kind = MUL; break;
	case DIV: code.kind = DIV; break;
	default: return;
	}
	code.u.binop.result = res;
	code.u.binop.op1 = op1;
	code.u.binop.op2 = op2;
	ir_codes[ir_count++] = code;
}

void gen_ifgoto(Operand x, Operand relop, Operand y, Operand z) {
	InterCode code;
	code.kind = IF_GOTO;
	code.u.cond.x = x;
	code.u.cond.relop = relop;
	code.u.cond.y = y;
	code.u.cond.z = z;
	ir_codes[ir_count++] = code;
}

void gen_label(Operand label) {
	InterCode code;
	code.kind = LABEL_IR;
	code.u.label.label = label;
	ir_codes[ir_count++] = code;
}

void gen_goto(Operand label) {
	InterCode code;
	code.kind = GOTO;
	code.u.jump.target = label;
	ir_codes[ir_count++] = code;
}

void gen_dec(Operand var, int size) {
	InterCode code;
	code.kind = DEC;
	code.u.dec.var = var;
	code.u.dec.size = size;
	ir_codes[ir_count++] = code;
}

void gen_call(Operand res, Operand func) {
	InterCode code;
	code.kind = CALL;
	code.u.call.ret = res;
	code.u.call.func = func;
	ir_codes[ir_count++] = code;
}

void gen_return(Operand val) {
	InterCode code;
	code.kind = RETURN;
	code.u.ret.ret_val = val;
	ir_codes[ir_count++] = code;
}

void gen_arg(Operand arg) {
	InterCode code;
	code.kind = ARG;
	code.u.arg.arg = arg;
	ir_codes[ir_count++] = code;
}

// 生成 PARAM 指令
void gen_param(Operand param) {
    InterCode code;
    code.kind = PARAM;
    code.u.param.param = param;
    ir_codes[ir_count++] = code;
}


// READ/WRITE 指令支持
void gen_read(Operand dest) {
    InterCode code;
    code.kind = READ;
    code.u.io.var = dest;
    ir_codes[ir_count++] = code;
}

void gen_write(Operand src) {
    InterCode code;
    code.kind = WRITE;
    code.u.io.var = src;
    ir_codes[ir_count++] = code;
}

char* operand_to_str(Operand op) {
    if (!op) return strdup("<null>");

    char* buffer = malloc(128); // 分配足够空间
    switch (op->kind) {
        case VARIABLE:
        case RELOP:
            snprintf(buffer, 128, "%s", op->u.name);
            break;
        case CONSTANT:
            snprintf(buffer, 128, "#%d", op->u.value);
            break;
        case LABEL:
            snprintf(buffer, 128, "%s", op->u.name);
            break;
        case ADDRESS:
            snprintf(buffer, 128, "&%s", op->u.name);
            break;
        default:
            snprintf(buffer, 128, "<?>");
            break;
    }
    return buffer; // 调用者必须free
}



// 辅助函数：打印单条中间代码到指定文件流
void print_code(FILE* fp, InterCode code) {
    switch (code.kind) {
    case ASSIGN: {
        char* left = operand_to_str(code.u.assign.left);
        char* right = operand_to_str(code.u.assign.right);
        fprintf(fp, "%s := %s\n", left, right);
        free(left);
        free(right);
        break;
    }
    case ADD: {
        char* res = operand_to_str(code.u.binop.result);
        char* op1 = operand_to_str(code.u.binop.op1);
        char* op2 = operand_to_str(code.u.binop.op2);
        fprintf(fp, "%s := %s + %s\n", res, op1, op2);
        free(res);
        free(op1);
        free(op2);
        break;
    }
    case SUB: {
        char* res = operand_to_str(code.u.binop.result);
        char* op1 = operand_to_str(code.u.binop.op1);
        char* op2 = operand_to_str(code.u.binop.op2);
        fprintf(fp, "%s := %s - %s\n", res, op1, op2);
        free(res);
        free(op1);
        free(op2);
        break;
    }
    case MUL: {
        char* res = operand_to_str(code.u.binop.result);
        char* op1 = operand_to_str(code.u.binop.op1);
        char* op2 = operand_to_str(code.u.binop.op2);
        fprintf(fp, "%s := %s * %s\n", res, op1, op2);
        free(res);
        free(op1);
        free(op2);
        break;
    }
    case DIV: {
        char* res = operand_to_str(code.u.binop.result);
        char* op1 = operand_to_str(code.u.binop.op1);
        char* op2 = operand_to_str(code.u.binop.op2);
        fprintf(fp, "%s := %s / %s\n", res, op1, op2);
        free(res);
        free(op1);
        free(op2);
        break;
    }
    case LABEL_IR: {
        char* label = operand_to_str(code.u.label.label);
        fprintf(fp, "LABEL %s :\n", label);
        free(label);
        break;
    }
    case FUNC: {
        char* func = operand_to_str(code.u.function.func);
        fprintf(fp, "FUNCTION %s :\n", func);
        free(func);
        break;
    }
    case GOTO: {
        char* target = operand_to_str(code.u.jump.target);
        fprintf(fp, "GOTO %s\n", target);
        free(target);
        break;
    }
    case IF_GOTO: {
        char* x = operand_to_str(code.u.cond.x);
        char* relop = operand_to_str(code.u.cond.relop);
        char* y = operand_to_str(code.u.cond.y);
        char* z = operand_to_str(code.u.cond.z);
        fprintf(fp, "IF %s %s %s GOTO %s\n", x, relop, y, z);
        free(x);
        free(relop);
        free(y);
        free(z);
        break;
    }
    case RETURN: {
        char* ret_val = operand_to_str(code.u.ret.ret_val);
        fprintf(fp, "RETURN %s\n", ret_val);
        free(ret_val);
        break;
    }
    case DEC: {
        char* var = operand_to_str(code.u.dec.var);
        fprintf(fp, "DEC %s %d\n", var, code.u.dec.size);
        free(var);
        break;
    }
    case ARG: {
        char* arg = operand_to_str(code.u.arg.arg);
        fprintf(fp, "ARG %s\n", arg);
        free(arg);
        break;
    }
    case PARAM: {
        char* param = operand_to_str(code.u.param.param);
        fprintf(fp, "PARAM %s\n", param);
        free(param);
        break;
    }
    case CALL: {
        char* ret = operand_to_str(code.u.call.ret);
        char* func = operand_to_str(code.u.call.func);
        fprintf(fp, "%s := CALL %s\n", ret, func);
        free(ret);
        free(func);
        break;
    }
    case READ: {
        char* var = operand_to_str(code.u.io.var);
        fprintf(fp, "READ %s\n", var);
        free(var);
        break;
    }
    case WRITE: {
        char* var = operand_to_str(code.u.io.var);
        fprintf(fp, "WRITE %s\n", var);
        free(var);
        break;
    }
    default: {
        fprintf(fp, "Unhandled code type: %d\n", code.kind);
        break;
    }
    }
}

void test_ir_generation() {

	// printf("===== Comprehensive IR Generation Test =====\n");
	// ir_count = 0; // 重置计数器

	// /*--------------------- 测试数据准备 ---------------------*/
	// // 基本操作数
	// Operand var_x = create_var_operand("x");
	// Operand var_y = create_var_operand("y");
	// Operand temp1 = create_var_operand("t1");
	// Operand const_5 = create_const_operand(5);
	// Operand const_0 = create_const_operand(0);

	// // 控制流相关
	// Operand label1 = create_label_operand(1);
	// Operand label2 = create_label_operand(2);
	// Operand relop_lt = create_relop_operand("<");

    // //函数相关
	// Operand func_main = create_var_operand("main");
	// Operand array_a = create_var_operand("arr");

	// /*--------------------- 测试用例执行 ---------------------*/
	// // 测试1: 基本运算和赋值
	// gen_assign(var_x, const_5);             // x := #5
	// gen_binop(ADD, temp1, var_x, var_y);    // t1 := x + y
	// gen_binop(MUL, var_x, temp1, const_5);  // x := t1 * #5

	// // 测试2: 控制流
	// gen_label(label1);                      // LABEL label1:
	// gen_ifgoto(var_x, relop_lt, var_y, label2); // IF x < y GOTO label2
	// gen_goto(label1);                       // GOTO label1
	// gen_label(label2);                      // LABEL label2:

	// // 测试3: 内存分配
	// gen_dec(array_a, 20);                   // DEC arr 20

	// // 测试4: 函数调用
	// gen_arg(var_x);                         // ARG x
	// gen_call(temp1, func_main);             // t1 := CALL main
	// gen_return(temp1);                      // RETURN t1

	/*--------------------- 结果验证 ---------------------*/
    // 打开文件
    FILE* fp = fopen("output.ir", "w");
    if (!fp) {
        fprintf(stderr, "Error: Failed to open output.ir for writing.\n");
        exit(1);
    }

    // 写入文件头
    // fprintf(fp, "\n[Generated IR Codes]\n");


	printf("\n[Generated IR Codes]\n");
	for (int i = 0; i < ir_count; i++) {
        // fprintf(fp, "%3d: ", i + 1); // 格式化为3位对齐的行号
        print_code(fp, ir_codes[i]);
        
        printf("%3d: ", i + 1);
        print_code(stdout, ir_codes[i]);
    }
	/*--------------------- 内存清理 ---------------------*/
	// free_operand(var_x);
	// free_operand(var_y);
	// free_operand(temp1);
	// free_operand(const_5);
	// free_operand(const_0);
	// free_operand(label1);
	// free_operand(label2);
	// free_operand(relop_lt);
	// free_operand(func_main);
	// free_operand(array_a);

    // 写入文件尾
    // fprintf(fp, "\n===== Test Completed =====\n");
    // 关闭文件
    fclose(fp);

	printf("\n===== Test Completed =====\n");

}

/*--------------------- 基础结构翻译 ---------------------*/
/* Program : ExtDefList */
void translate_Program(ParseNode Program) {
    printf("[DEBUG] Enter translate_Program\n"); // 添加调试输出
    if (!Program || !Program->child[0]) {
        printf("Error: Invalid Program node\n");
        return;
    }

    translate_ExtDefList(Program->child[0]);
}

/* ExtDefList : ExtDef ExtDefList | ε */
void translate_ExtDefList(ParseNode ExtDefList) {
    printf("[DEBUG] Enter translate_ExtDefList\n"); // 添加调试输出

    if (ExtDefList->num <= 0) return; // ε情况
    
    // printf("%d, %s |\n",5 ,ExtDefList->child[0]->name);
    
    translate_ExtDef(ExtDefList->child[0]);
    translate_ExtDefList(ExtDefList->child[1]);
}

/* ParamDec : Specifier VarDec */
void translate_ParamDec(ParseNode ParamDec) {
    // 生成参数声明（VarDec是简单变量）
    ParseNode VarDec = ParamDec->child[1];
    Operand var = create_var_operand(VarDec->child[0]->ID); // 获取变量名

    Symbol* sym = find_symbol(VarDec->child[0]->ID); // 查找符号表条目
    sym->operand = create_var_operand(VarDec->child[0]->ID);

    gen_param(var); // 参数传递指令
}

/* VarDec : ID | VarDec LB INT RB */
void translate_VarDec(ParseNode VarDec) {
    printf("[DEBUG] Enter translate_VarDec\n"); // 添加调试输出
    if (VarDec->num == 1) { // 简单变量
        char* var_name = VarDec->child[0]->ID;
        printf("[DEBUG] Declaring variable: %s\n", var_name); // 确认变量名
        Symbol* sym = find_symbol(var_name); // 查找符号表条目

        printf("[SYMBOL] Find symbol '%s' in scope %p\n", var_name, (void*)current_scope);
        printf("[SYMBOL] Symbol '%s' operand: %p\n", var_name, (void*)sym->operand);

        if (!sym) {
            fprintf(stderr, "Error: Failed to add symbol '%s'\n", var_name);
            exit(1);
        }

        
        if (!sym->operand) { // 仅当操作数不存在时创建
            sym->operand = create_var_operand(var_name);
            printf("[DEBUG] Created new operand for %s\n", var_name);
        } else {
            printf("[DEBUG] Reusing existing operand for %s\n", var_name);
        }

        return;
    }
    // 数组声明：生成DEC指令
    int size = 4; // 基础类型大小
    ParseNode intNode = VarDec->child[2];
    int array_size = intNode->INT * size; 
    Operand var = create_var_operand(VarDec->child[0]->child[0]->ID);
    gen_dec(var, array_size);
}

/* CompSt : LC DefList StmtList RC */
void translate_CompSt(ParseNode CompSt) {
    translate_DefList(CompSt->child[1]); // 局部定义
    translate_StmtList(CompSt->child[2]); // 语句列表
}

/* StmtList : Stmt StmtList | ε */ 
void translate_StmtList(ParseNode StmtList) {
    if (StmtList->num <= 0) {
        printf("[DEBUG] StmtList is empty\n");
        return;
    }

    // 打印当前 StmtList 结构
    printf("[DEBUG] StmtList has %d children:\n", StmtList->num);
    for (int i = 0; i < StmtList->num; i++) {
        if (StmtList->child[i]) {
            printf("  Child %d: %s\n", i, StmtList->child[i]->name);
        } else {
            printf("  Child %d: NULL\n", i);
        }
    }

    translate_Stmt(StmtList->child[0]);

    printf("hello-------------------\n");  // 调试输出
    
    translate_StmtList(StmtList->child[1]);
}

/* Def : Specifier DecList SEMI */
void translate_Def(ParseNode Def) {
    translate_DecList(Def->child[1]); // 处理声明列表
}

/* Dec : VarDec | VarDec ASSIGNOP Exp */
void translate_Dec(ParseNode Dec) {
    printf("[DEBUG] Enter translate_Dec\n");

    translate_VarDec(Dec->child[0]);
    if (Dec->num == 3) { // 带初始化
        // 直接使用create_var_operand生成临时变量
        char temp_name[20];
        sprintf(temp_name, "t%d", temp_counter++); // 使用静态计数器
        Operand temp = create_var_operand(temp_name);
        
        translate_Exp(Dec->child[2], temp);

        

        if (Dec->child[0] && Dec->child[0]->child[0]) {
            char* var_name = Dec->child[0]->child[0]->ID;
            // 从符号表获取操作数，而不是新建
            Symbol* sym = find_symbol(var_name);
            if (!sym) {
                fprintf(stderr, "Error: Symbol '%s' not found\n", var_name);
                exit(1);
            }
            gen_assign(sym->operand, temp); // 使用符号表中的操作数
        }        
    }
}

/* DecList : Dec | Dec COMMA DecList */
void translate_DecList(ParseNode DecList) {

    // printf("%d, %s |\n",2 ,DecList->child[0]->name);

    translate_Dec(DecList->child[0]);
    if (DecList->num == 3) {
        translate_DecList(DecList->child[2]);
    }
}

/*--------------------- 函数相关 ---------------------*/
/* FunDec : ID LP VarList RP | ID LP RP */
void translate_FunDec(ParseNode FunDec) {
    // 生成函数标签
    Operand func = create_var_operand(FunDec->child[0]->ID);
    
    // 生成FUNCTION声明
    InterCode func_code;
    func_code.kind = FUNC;
    func_code.u.function.func = func;
    ir_codes[ir_count++] = func_code;
    
    // 生成标签定位
    // gen_label(func);

    // print_code(func_code);
    
    if (FunDec->num == 4) { // 带参数
        translate_VarList(FunDec->child[2]);
    }
}


/* VarList : ParamDec COMMA VarList | ParamDec */
void translate_VarList(ParseNode VarList) {
    translate_ParamDec(VarList->child[0]);
    if (VarList->num == 3) {
        translate_VarList(VarList->child[2]);
    }
}

/*--------------------- 扩展定义 ---------------------*/
/* ExtDef : Specifier ExtDecList SEMI | Specifier FunDec CompSt*/
void translate_ExtDef(ParseNode ExtDef) {
    if (strcmp(ExtDef->child[1]->name, "ExtDecList") == 0) {
        translate_ExtDecList(ExtDef->child[1]); // 全局变量声明
    }
    else if (strcmp(ExtDef->child[1]->name, "FunDec") == 0) {

        // printf("%d, %s |\n",5 ,ExtDef->child[0]->name);

        translate_FunDec(ExtDef->child[1]); // 全局变量声明
        translate_CompSt(ExtDef->child[2]);
    }
}

/* ExtDecList : VarDec | VarDec COMMA ExtDecList */
void translate_ExtDecList(ParseNode ExtDecList) {
    translate_VarDec(ExtDecList->child[0]);
    if (ExtDecList->num == 3) {
        translate_ExtDecList(ExtDecList->child[2]);
    }
}

/*--------------------- Exp 表达式翻译 ---------------------*/
// Exp : Exp ASSIGNOP Exp
//     | Exp AND Exp
//     | Exp OR Exp
//     | Exp RELOP Exp
//     | Exp PLUS Exp
//     | Exp MINUS Exp
//     | Exp STAR Exp
//     | Exp DIV Exp
//     | LP Exp RP
//     | MINUS Exp
//     | NOT Exp
//     | ID LP Args RP
//     | ID LP RP
//     | Exp LB Exp RB
//     | Exp DOT ID
//     | ID
//     | INT
//     | FLOAT

// 生成新临时变量名
const char* new_temp_name() {
    static int counter = 1;
    char* name = (char*)malloc(20);
    sprintf(name, "t%d", counter++);
    return name;
}

void translate_Exp(ParseNode Exp, Operand place) {
    printf("[DEBUG] Enter translate_Exp\n"); // 添加调试输出
    if (Exp->num == 3 && strcmp(Exp->child[1]->name, "ASSIGNOP") == 0) {
        printf("[DEBUG] Processing assignment\n");
        
        
        // ==== 核心修改：直接生成右值到新临时变量 ====
        Operand right_temp = create_var_operand(new_temp_name());
        translate_Exp(Exp->child[2], right_temp);
        
        // 处理左值（必须是变量）
        if (Exp->child[0]->child[0] && 
            strcmp(Exp->child[0]->child[0]->name, "ID") == 0) 
        {
            char* var_name = Exp->child[0]->child[0]->ID;
            Symbol* sym = find_symbol(var_name);
            if (!sym || !sym->operand) {
                fprintf(stderr, "Error: Variable '%s' not declared\n", var_name);
                exit(1);
            }
            
            // 生成赋值指令
            gen_assign(sym->operand, right_temp);
            
            // 如果外部需要结果，传递临时变量的值
            if (place) {
                gen_assign(place, right_temp);
            }
        }
    }
    else if (Exp->num == 3 && strcmp(Exp->child[1]->name, "PLUS") == 0) {
        // 处理加法 Exp -> Exp PLUS Exp
        char temp_name[20];

        sprintf(temp_name, "t%d", temp_counter++);
        Operand t1 = create_var_operand(temp_name);
        sprintf(temp_name, "t%d", temp_counter++);
        Operand t2 = create_var_operand(temp_name);

        translate_Exp(Exp->child[0], t1);
        translate_Exp(Exp->child[2], t2);
        gen_binop(ADD, place, t1, t2);
    }
    else if (Exp->num == 3 && strcmp(Exp->child[1]->name, "MINUS") == 0) {
        // Exp -> Exp MINUS Exp
        char temp_name[20];

        sprintf(temp_name, "t%d", temp_counter++);
        Operand t1 = create_var_operand(temp_name);
        sprintf(temp_name, "t%d", temp_counter++);
        Operand t2 = create_var_operand(temp_name);

        translate_Exp(Exp->child[0], t1);
        translate_Exp(Exp->child[2], t2);
        gen_binop(SUB, place, t1, t2);
    }
    else if (Exp->num == 3 && strcmp(Exp->child[1]->name, "STAR") == 0) {
        char temp_name[20];

        sprintf(temp_name, "t%d", temp_counter++);
        Operand t1 = create_var_operand(temp_name);
        sprintf(temp_name, "t%d", temp_counter++);
        Operand t2 = create_var_operand(temp_name);

        translate_Exp(Exp->child[0], t1);
        translate_Exp(Exp->child[2], t2);
        gen_binop(MUL, place, t1, t2);
    }
    else if (Exp->num == 3 && strcmp(Exp->child[0]->name, "LP") == 0 && strcmp(Exp->child[2]->name, "RP") == 0) 
    {
        printf("[DEBUG] Processing parenthesized expression--------------------------------------------\n");
        // 直接递归处理内部的 Exp
        translate_Exp(Exp->child[1], place);
        return;
    }
    else if (Exp->num == 3 && strcmp(Exp->child[0]->name, "ID") == 0) {
        // 处理无参数的函数调用（read()）
        char* func_name = Exp->child[0]->ID;
        if (strcmp(func_name, "read") == 0) {
            // 生成 READ 指令
            gen_read(place);
        } else {
            // 普通无参函数调用
            gen_call(place, create_var_operand(func_name));
        }
    }
    else if (Exp->num == 4 && strcmp(Exp->child[0]->name, "ID") == 0) {
        // 处理带参数的函数调用（如 write(1)）
        char* func_name = Exp->child[0]->ID;
        if (strcmp(func_name, "write") == 0) {
            // 处理参数
            Operand args[1];
            int arg_count = 0;
            translate_Args(Exp->child[2], args, &arg_count);
            gen_write(args[0]); // gen_write 函数
        } else {
            // 普通带参函数调用
            Operand args[10];
            int arg_count = 0;

            translate_Args(Exp->child[2], args, &arg_count);

            for (int i = arg_count-1; i >=0; i--) gen_arg(args[i]);
            gen_call(place, create_var_operand(func_name));
        }
    }
    else if (Exp->num == 2 && strcmp(Exp->child[0]->name, "MINUS") == 0) {
        printf("[DEBUG] Processing unary minus (-Exp)\n");
        
        // 生成临时变量保存子表达式结果
        char temp_name[20];
        sprintf(temp_name, "t%d", temp_counter++);
        Operand temp = create_var_operand(temp_name);
        
        // 递归翻译子表达式（如 n）
        translate_Exp(Exp->child[1], temp);
        
        // 生成 0 - temp 的减法操作
        Operand zero = create_const_operand(0);
        gen_binop(SUB, place, zero, temp);
    }
    else if (Exp->num == 1 && strcmp(Exp->child[0]->name, "ID") == 0) {
        // 简单变量引用
        Symbol* sym = find_symbol(Exp->child[0]->ID);

        if (!sym || !sym->operand) {
            printf("[ERROR] Invalid symbol or operand for ID '%s'\n", Exp->child[0]->ID);
            return;
        }
        
        // 仅当place有效时才生成赋值
        if (place) {
            gen_assign(place, sym->operand);
        } else {
            printf("[DEBUG] Ignoring assignment to NULL place\n");
        }
    }
    else if (Exp->num == 1 && strcmp(Exp->child[0]->name, "INT") == 0) {
        // 常量处理
        Operand c = create_const_operand(Exp->child[0]->INT);
        gen_assign(place, c);
    }
}

/*--------------------- Args 参数列表翻译 ---------------------*/
// Args : Exp COMMA Args | Exp
void translate_Args(ParseNode Args, Operand *arg_list, int *num) {
    if (!Args) return;

    if (Args->num == 1) { // Exp -> 单参数
        // 生成唯一临时变量名
        char temp_name[20];
        sprintf(temp_name, "t%d", temp_counter++);
        Operand arg = create_var_operand(temp_name);
        
        // 翻译表达式并存入参数列表
        translate_Exp(Args->child[0], arg);

        printf("%s-------------------------\n",Args->child[0]->name);

        arg_list[(*num)++] = arg;
    }
    else if (Args->num == 3) { // Exp COMMA Args -> 多参数
        // 递归处理后续参数
        translate_Args(Args->child[2], arg_list, num);
        // 处理当前Exp（保证参数顺序）
        char temp_name[20];
        sprintf(temp_name, "t%d", temp_counter++);
        Operand arg = create_var_operand(temp_name);
        translate_Exp(Args->child[0], arg);
        arg_list[(*num)++] = arg;
    }
}

/*--------------------- Cond 条件表达式翻译 ---------------------*/
void translate_Cond(ParseNode Exp, Operand label_true, Operand label_false) {
    if (Exp->num == 3 && strcmp(Exp->child[1]->name, "RELOP") == 0) {
        // 处理关系运算
        char temp_name[20];

        sprintf(temp_name, "t%d", temp_counter++);
        Operand t1 = create_var_operand(temp_name);
        sprintf(temp_name, "t%d", temp_counter++);
        Operand t2 = create_var_operand(temp_name);

        translate_Exp(Exp->child[0], t1);
        translate_Exp(Exp->child[2], t2);
        
        Operand relop = create_relop_operand(Exp->child[1]->ID);
        gen_ifgoto(t1, relop, t2, label_true);
        gen_goto(label_false);
    }
    else if (Exp->num == 3 && strcmp(Exp->child[1]->name, "AND") == 0) {
        // 处理逻辑与
        Operand label = create_label_operand(label_counter++);
        translate_Cond(Exp->child[0], label, label_false);
        gen_label(label);
        translate_Cond(Exp->child[2], label_true, label_false);
    }
    else if (Exp->num == 3 && strcmp(Exp->child[1]->name, "OR") == 0) {
        // 处理逻辑或
        Operand label = create_label_operand(label_counter++);
        translate_Cond(Exp->child[0], label_true, label);
        gen_label(label);
        translate_Cond(Exp->child[2], label_true, label_false);
    }
}

/*--------------------- Stmt 语句翻译 ---------------------*/
// Stmt -> Exp SEMI +
//       | CompSt +
//       | RETURN Exp SEMI +
//       | IF LP Exp RP Stmt 
//       | IF LP Exp RP Stmt ELSE Stmt +
//       | WHILE LP Exp RP Stmt +

void translate_Stmt(ParseNode Stmt) {
    if (Stmt->num == 1 && strcmp(Stmt->child[0]->name, "CompSt") == 0) {
        translate_CompSt(Stmt->child[0]);
    }
    else if (Stmt->num == 2 && strcmp(Stmt->child[0]->name, "Exp") == 0){
        printf("[DEBUG] Processing Exp statement (no return value)\n");
        printf("[DEBUG] ==== BEFORE translate_Exp ====\n");
        translate_Exp(Stmt->child[0], NULL);
        printf("[DEBUG] ==== AFTER translate_Exp ====\n");
    }
    else if (Stmt->num == 3 && strcmp(Stmt->child[0]->name, "RETURN") == 0) {
        // RETURN Exp;
        char temp_name[20];
        sprintf(temp_name, "t%d", temp_counter++);
        Operand t = create_var_operand(temp_name);

        translate_Exp(Stmt->child[1], t);
        gen_return(t);
    }
    else if (Stmt->num == 5 && strcmp(Stmt->child[0]->name, "WHILE") == 0) {
        // WHILE (Exp) Stmt
        Operand label_start = create_label_operand(label_counter++);
        Operand label_cond = create_label_operand(label_counter++);
        Operand label_end = create_label_operand(label_counter++);
        
        gen_label(label_start);
        gen_goto(label_cond);
        gen_label(label_cond);
        translate_Cond(Stmt->child[2], label_start, label_end);
        gen_label(label_start);
        translate_Stmt(Stmt->child[4]);
        gen_goto(label_cond);
        gen_label(label_end);
    }
    else if (Stmt->num == 7 && strcmp(Stmt->child[0]->name, "IF") == 0) {
        // IF (Exp) Stmt ELSE Stmt
        Operand label1 = create_label_operand(label_counter++);
        Operand label2 = create_label_operand(label_counter++);
        Operand label_end = create_label_operand(label_counter++);
        
        translate_Cond(Stmt->child[2], label1, label2);
        gen_label(label1);
        translate_Stmt(Stmt->child[4]);
        gen_goto(label_end);
        gen_label(label2);
        translate_Stmt(Stmt->child[6]);
        gen_label(label_end);
    }
}

/*--------------------- DefList : Def DefList | ε---------------------*/
void translate_DefList(ParseNode DefList) {
    if (DefList->num == 2) { // Def DefList
        translate_Def(DefList->child[0]);
        translate_DefList(DefList->child[1]);
    }
    // ε情况不处理
}
